#include "CServer.hpp"
#include "AsioIoContextPool.hpp"
#include "HttpConnection.hpp"
#include <boost/asio/ip/tcp.hpp>
#include <iostream>
#include <memory>
CServer::CServer(boost::asio::io_context &ioc, unsigned short &port)
    : _ioc(ioc), _acceptor(ioc, tcp::endpoint(tcp::v4(), port)) {}

void CServer::Start() {
  auto self = shared_from_this();
  // ioContext池
  auto &ioc = AsioIoContextPool::GetInstance()->GetIoContext();
  auto httpConnection = std::make_shared<HttpConnection>(ioc);
  _acceptor.async_accept(httpConnection->GetSocket(),
                         [self, httpConnection](boost::system::error_code ec) {
                           try {
                             // 出现错误
                             if (ec) {
                               self->Start();
                               return;
                             }
                             // 处理http链接
                             httpConnection->Start();
                             // 继续监听链接
                             self->Start();
                           } catch (std::exception &e) {
                             std::cerr << e.what() << "\n";
                           }
                         });
}